﻿namespace Grep.Lib.Extensions
{
    public static class StringExtensions
    {
        public static string GreedyAppend(this string self, string postfix, bool keepTrimmedPostfixOnly)
        {
            for (int startIndex = 0; startIndex < self.Length; ++startIndex)
            {
                int toMatch = self.Length - startIndex;
                if (toMatch > postfix.Length)
                {
                    continue;
                }
                bool match = true;
                for (int matchIndex = 0; matchIndex < toMatch; ++matchIndex)
                {
                    if (self[startIndex + matchIndex] != postfix[matchIndex])
                    {
                        match = false;
                        break;
                    }
                }
                if (match)
                {
                    string mergedString = self.Substring(0, startIndex) + postfix;
                    return keepTrimmedPostfixOnly ? mergedString.Remove(0, self.Length) : mergedString;
                }
            }
            return (keepTrimmedPostfixOnly ? "" : self) + postfix;
        }
    }
}